import { type ReactNode, useEffect, useState } from "react";
import { Settings as SettingsIcon } from "lucide-react";
import { useSnapshot } from "valtio";
import NavLink from "./components/NavLink";
import Search from "./components/Search";
import Setting from "./components/Setting";
import { Button } from "./components/ui/button";
import { Card, CardContent } from "./components/ui/card";
import { coreState } from "./store/core";
import { storage } from "./store/storage";
import { getEnvironment } from "./utils/environment";

export default function App() {
  const snapCore = useSnapshot(coreState);

  const [showSettings, setShowSettings] = useState(false);
  const [loaded, setLoaded] = useState(false);

  async function initSettings() {
    const settings = await storage.get();
    coreState.setSettings(settings, false);
  }

  useEffect(() => {
    setLoaded(true);
    initSettings();

    // 添加平滑滚动
    document.documentElement.style.scrollBehavior = "smooth";
  }, []);

  const renderCard = (child: ReactNode) => {
    return (
      <Card
        className={`backdrop-blur-sm bg-background/70 border-border/50 ${loaded ? "animate-fade-in" : "opacity-0"} animate-delay-[300ms]`}
      >
        <CardContent>{child}</CardContent>
      </Card>
    );
  };
  return (
    <>
      <div
        className={`min-h-dvh w-full overflow-x-hidden bg-background text-foreground font-sans transition-colors duration-500 ${
          snapCore.settings.background ? "bg-cover bg-center bg-fixed" : "bg-gradient-to-b from-gray-900 to-gray-800"
        }`}
        style={{ backgroundImage: snapCore.settings.background ? `url(${snapCore.settings.background})` : undefined }}
      >
        <div className="min-h-dvh relative">
          <div className="absolute inset-0 bg-gradient-to-b from-background/80 to-background/20 pointer-events-none"></div>
          <div className="relative max-w-[80vw] mx-auto p-4">
            <div className="fixed top-8 right-8 z-50 flex items-center gap-2">
              <span className="text-xs px-2 py-1 rounded-full bg-background/80 backdrop-blur-lg text-foreground/80">
                {getEnvironment() === "extension" ? "Extension" : "Web"}
              </span>
              <Button
                variant="ghost"
                size="icon"
                className="bg-background/80 hover:bg-accent backdrop-blur-lg rounded-full w-14 h-14 shadow-lg transition-all duration-300 hover:scale-110 hover:shadow-xl"
                onClick={() => setShowSettings(true)}
              >
                <SettingsIcon className="h-6 w-6" />
              </Button>
            </div>

            <div className="space-y-4">
              {renderCard(<Search />)}
              {renderCard(<NavLink />)}
            </div>
          </div>
        </div>
      </div>

      <Setting open={showSettings} onClose={() => setShowSettings(false)} />
    </>
  );
}
